# code to make figure 1
library(here)

here::here()

source("code/startup.R")
library(parrot)

rfs <- readr::read_csv("data/dat_scored.csv")

rg_cands <- as_tibble(rfs) %>%
  mutate(race_gen = case_when(race.a ==1 & gen.a ==1 ~ "White Men",
                              race.a ==1 & gen.a ==0 ~ "White Women",
                              race.a ==0 & gen.a ==1 ~ "Men of Color",
                              race.a ==0 & gen.a ==0 ~ "Women of Color")) %>%
  group_by(race_gen) %>%
  summarise(n_total = n(),
            n_running = sum(running),
            prop_running = mean(running)) %>%
  ungroup() %>%
  mutate(n_not_running = n_total - n_running,
         prop_cands = n_running / sum(n_running),
         prop_total = n_total / sum(n_total))

f1_bars <-
  rg_cands %>%
  arrange(desc(n_running)) %>%
  mutate(lab = paste0(n_running, " of ", n_total," (", round(prop_running*100, 0),"%) running"),
         xlabel = paste0(race_gen, "\n(", round(prop_total*100, 0), "% of respondents)")) %>%
  dplyr::select(race_gen, n_total, n_running, lab, xlabel) %>%
  reshape2::melt(id.vars = c("race_gen","lab","xlabel")) %>%
  ggplot()+
  geom_col(aes(x = fct_rev(fct_inorder(xlabel)),
               y = value, fill = variable), col = "black")+
  #geom_col(aes(x = fct_rev(fct_inorder(race_gen)),
  #             y = n_running), fill = "grey", col = "black")+
  geom_text(aes(x = fct_rev(fct_inorder(xlabel)),
                y = 2500,
                label = lab))+
  scale_fill_manual(name = "",
                     breaks = c("n_total","n_running"),
                    values = c("white","grey"),
                     labels = c("All Respondents","Candidates"))+
  coord_flip()+
  labs(x = "", y = "Number of Respondents",
       title = "Candidate Emergence by Race and Gender",
       caption = "Note: 6,943 (67%) of respondents have race and gender either reported or identified on the voter file; remaining values assigned probabilistically")+
  theme_jg()+
  theme(plot.caption = element_text(hjust = 0.3))
ggsave(f1_bars, file = "figures/f1_bars.png", width = 12, height = 4)
